<!--
 * @Author: caofujun
 * @Date: 2021-01-27 15:07:00
 * @Description: 列表筛选导出
-->
<template>
  <div>
    <el-button type="" icon="el-icon-download" @click="dialogVisible=true;">{{ exportName }}</el-button>
    <el-dialog
      title="导出筛选订单"
      :visible.sync="dialogVisible"
      width="800px"
      :before-close="dialogBeforeClose"
    >
      <div v-if="crud.data && crud.data.list" v-loading="downLoading">
        <el-button :loading="loading" :disabled="exportDisabled" type="primary" @click="exportHandleClick">导出筛选订单</el-button>
        <span class="cl-999 fs-12 ml-10">{{ exportDisabled ? '请选择筛选条件进行导出' : '导出当前筛选条件下的订单' }}</span>
        <el-table
          class="mt-10"
          :data="crud.data.list"
          style="width: 100%"
          header-row-class-name="table_header_antd"
        >
          <el-table-column label="编号">
            <template slot-scope="scope">
              <span>{{ scope.$index | indexMethod(crud.page.page, crud.page.size) }}</span>
            </template>
          </el-table-column>

          <el-table-column label="导出时间">
            <template slot="header" slot-scope="">
              <el-tooltip class="item" effect="dark" content="已生成的订单明细保留 7天有效期" placement="top">
                <span>导出时间 <i class="el-icon-question" style="font-size:14px; color:#000" /></span>
              </el-tooltip>
            </template>
            <template slot-scope="scope">
              <div>
                {{ parseTime(scope.row.createTime) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <div
                v-loading="scope.row.state !== CONFIG.EXPORT_STATE.finsh"
                :style="scope.row.state !== CONFIG.EXPORT_STATE.finsh ? 'height:50px' : ''"
                element-loading-text="正在拼命生成，请稍后"
                element-loading-spinner="el-icon-loading"
              >
                <el-button
                  type="text"
                  @click="downloadHandlerClick(scope.row)"
                >下载明细</el-button>
              </div>
            </template>

          </el-table-column>

        </el-table>
        <pagination crud-tag="FilterExportExcelTag" />
      </div>
      <div v-else class="text-center flex-all-center" style="min-height:400px">
        <div>
          <el-button :loading="loading" type="primary" :disabled="exportDisabled" @click="exportHandleClick">导出筛选订单</el-button>
          <p class="mt-30 cl-666">{{ exportDisabled ? '请选择筛选条件进行导出' : '导出当前筛选条件下的订单' }}</p>
          <p class="cl-666">已生成的订单明细保留 7天有效期</p>
        </div>
      </div>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confrim">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CRUD, { presenter, header, crud } from '@crud/crud'
import pagination from '@crud/Pagination'
import { getMethodRequest } from '@/api/common'
import { propertyValidate } from '@/utils'
import CONFIG from './config'

let merageRequestConfig = { } // 请求集合   默认配置是退款管理导出接口
let timer = null
const MAX_REQUEST = 30 // 最大轮训请求次数
const MS = 5000
let COUNT = 0
export default {
  name: 'FilterExportExcel',
  components: { pagination },
  filters: {
    formatExportStatus(state, cloudState) { // 暂没用
      let str = ''
      if (cloudState === 1) return '已过期'
      switch (state) {
        case CONFIG.EXPORT_STATE.progress:
          str = '生成中'
          break
        case CONFIG.EXPORT_STATE.upload:
          str = '上传中'
          break
        case CONFIG.EXPORT_STATE.finsh:
          str = '已完成'
          break
        default:
          str = '未知'
          break
      }
      return str
    }
  },
  cruds() {
    return CRUD({
      tag: 'FilterExportExcelTag',
      title: '导出记录',
      url: 'admin/order/getExportOrderList',
      query: {
      },
      crudMethod: {}
    })
  },
  mixins: [presenter(), header(), crud()],
  props: {
    tag: {
      type: String,
      default: ''
    },
    exportName: {
      type: String,
      default: '导出订单'
    },
    requestObj: { // 请求集合 参数见变量（merageRequestConfig）
      type: Object,
      default: () => {
        return {
        }
      }
    },
    filterParams: { // 筛选条件参数
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      CONFIG,
      dialogVisible: false,
      loading: true,
      downLoading: false
    }
  },
  computed: {
    exportDisabled: function() {
      return !propertyValidate(this.filterParams)
    }
  },
  watch: {
    dialogVisible(val) {
      if (val) {
        this.init()
        merageRequestConfig = { ...merageRequestConfig, ...this.requestObj }
        this.crud.url = merageRequestConfig.historys.url
        this.crud.query = merageRequestConfig.historys.query
        this.crud.toQuery()
        this.getExportState()
      } else {
        if (this.loading) {
          this.$message.info('明细将继续生成…')
        }
      }
    }
  },
  mounted() {},
  methods: {
    confrim() {
      this.dialogVisible = false
    },
    dialogBeforeClose() {
      this.dialogVisible = false
    },
    init() {
      timer = null
      COUNT = 0
      merageRequestConfig = {
        exportState: {// 导出状态
          url: 'admin/order/getExportOrderState',
          query: { exportType: CONFIG.EXPORT_TYPE.order }
        },
        historys: { // 历史
          url: 'admin/order/getExportOrderList',
          query: { exportType: CONFIG.EXPORT_TYPE.order }
        },
        exportExcel: { url: 'admin/order/list' }, // 导出
        exportExcelById: { // 历史记录 导出通过id刷新数据
          url: 'supplier/order/exportExcelById'
        },
        exportExcelByDownloadUrl: { // 置换下载链接
          url: 'admin/order/getObsTemporarySignatureUrl'
        }
      }
    },
    async exportHandleClick() { // 导出
      try {
        this.loading = true
        console.log(this.filterParams)
        const params = JSON.parse(JSON.stringify(this.filterParams))
        if (params.createTime) {
          params.startTime = params.createTime[0]
          params.endTime = params.createTime[1]
          delete params.createTime
        }
        const res = await getMethodRequest(
          merageRequestConfig.exportExcel.url,
          { ...params, pageIndex: 1, exportOrder: true }
        )
        if (res.errorCode === 0) {
          this.crud.toQuery()
          this.getExportState()
        }
      } catch (error) {
        this.$message.error('导出异常')
        this.loading = false
        console.log(error)
      }
    },
    async getExportState() { // 查询导出状态
      try {
        if (timer) {
          clearTimeout(timer)
        }
        this.loading = true
        const res = await getMethodRequest(
          merageRequestConfig.exportState.url,
          merageRequestConfig.exportState.query
        )
        if (COUNT >= MAX_REQUEST) {
          this.loading = false
          return false
        }
        if (res.errorCode === 0) {
          if (JSON.stringify(res.data) === '{}') {
            this.loading = false
            return false // 列表空
          }

          switch (res.data.state) {
            case CONFIG.EXPORT_STATE.finsh:
              this.crud.toQuery()
              this.loading = false
              COUNT = 0
              break
            default:
              timer = setTimeout(() => {
                this.getExportState()
              }, MS)
              break
          }
        } else {
          this.$message.error('服务异常')
          this.loading = false
        }
        COUNT++
      } catch (error) {
        this.loading = false
        COUNT++
        console.log(error)
      }
    },
    async downloadHandlerClick(row) { // 下载
      console.log(row)
      // if (idx === 0 && this.crud.page.page === 1) { // 第一条直接导出
      //   window.open(row.downloadUrl)
      //   return false
      // }
      try {
        this.downLoading = true
        const res = await getMethodRequest(
          merageRequestConfig.exportExcelByDownloadUrl.url,
          { downloadLink: row.downloadLink }
        )
        if (res.errorCode === 0 && res.data.downloadLink) {
          window.open(res.data.downloadLink)
        }
        this.downLoading = false
      } catch (error) {
        this.downLoading = false

        console.log(error)
      }
    },
    destroyed() {
      clearTimeout(timer)
    },
    [CRUD.HOOK.beforeRefresh](crud) {
      return this.dialogVisible
    },
    [CRUD.HOOK.afterRefresh](crud) {

    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
/deep/ .table_header_antd {
  th {
    border-bottom: 1px solid #e8e8e8;
    border-top: 1px solid #e8e8e8;
    background-color: #fafafa;
    color: #262626;
    &:first-child {
      border-left: 1px solid #e8e8e8;
    }
    &:last-child {
      border-right: 1px solid #e8e8e8;
    }
  }
}
p{
  margin-bottom: 0;
}
</style>
